/*eslint-disable*/
import { Button } from "antd";
import React, { useState, useMemo, useCallback } from "react";
import "./UseMemoComp.less";

/**
 * 自定义hooks
 * @param initialState 初始状态
 * @returns 状态和设置状态的方法
 */
const usePartialState = (initialState: any) => {
  const [state, setState] = useState(initialState);
  const setPartialState = (newState: any) => {
    setState((prevState: any) => ({ ...prevState, ...newState }));
  };
  return [state, setPartialState];
};


interface ChildProps {
  handle: () => void;
}

// class Child extends React.PureComponent<ChildProps> {
//   render() {
//     console.log('Child RENDER')
//     return <div>Child</div>
//   }
// }

/**
 * 使用React.memo
 * 1. 依赖项发生变化时，Child会重新渲染
 * 2. 依赖项不发生变化时，Child不会重新渲染
 */
const Child = React.memo((props: ChildProps) => {
  interface Count {
    count: number,
    name: string,
    age: number,
    sex: string
  }
  const [count, setCount] = usePartialState({
    count: 0,
    name: '张三',
    age: 18,
    sex: '男'
  } as Count)
  const changeName = () => {
    setCount({
      name: '李四'
    })
  }
  return <div>{count.count}-{count.name}-{count.age}-{count.sex} <Button onClick={changeName}>改变</Button></div>
})

let prev: any
const UseMemoComp = () => {
  const [supNum, setSupNum] = useState(10);
  const [oppNum, setOppNum] = useState(5);
  const [x, setX] = useState(0);


  /**
   * 使用useCallback
   * let xxx = useCallback(callback, [依赖项])
   * 1. 依赖项发生变化时，callback才会执行
   * 2. 依赖项不发生变化时，callback不会执行
   * 3. 依赖项不发生变化时，xxx的值会从缓存中获取
   */
  const handle = useCallback(() => {
    console.log('handle')
  }, [])
  if (!prev) {
    prev = handle
  } else {
    console.log(handle === prev)
  }

  // let total = supNum + oppNum, ratio = '--'
  // if (total > 0) {
  //   console.log('useMemo')
  //   ratio = ((supNum / total) * 100).toFixed(2) + '%'
  // }

  /**
   * 使用useMemo
   * let xxx = useMemo(callback, [依赖项])
   * 1. 依赖项发生变化时，callback才会执行
   * 2. 依赖项不发生变化时，callback不会执行
   */
  const ratio = useMemo(() => {
    console.log('useMemo')
    let total = supNum + oppNum, ratio = '--'
    if (total > 0) {
      ratio = ((supNum / total) * 100).toFixed(2) + '%'
    }
    return ratio
  }, [supNum, oppNum])

  return (
    <div className="vote-box">
      <div className="main">
        <p>支持人数：{supNum}</p>
        <p>反对人数：{oppNum}</p>
        <p>支持比率：{ratio}</p>
        <p>x:{x}</p>
      </div>
      <div className="footer">
        <Button type="primary" onClick={() => setSupNum(supNum + 1)}>
          支持
        </Button>
        <Button type="primary" danger onClick={() => setOppNum(oppNum + 1)}>
          反对
        </Button>
        <Button style={{ marginTop: "20px" }} onClick={() => setX(x + 1)}>
          干点别的事
        </Button>
      </div>
      <Child handle={handle} />
    </div>
  );
};

export default UseMemoComp;
